<?php
/** 
 * 快递相关
 *
 * @author   xionggan
 * @date     2019-08-15
 */

namespace service;

use helper\LogHelper;
use think\Db;
use think\Validate;
use think\Exception;
use think\facade\Log;
use other\BaseRedis;
use app\common\model\CoreOrderDelivery;

class ExpressService
{

    public function __construct()
    {

    }

    /**
     * 查询用户最新包裹物流信息
     *
     * @param   number  $user_id    用户id
     * @return  array|null          物流数据
     */
    public function getUserLastFollow($user_id)
    {
        $delivery_model = new CoreOrderDelivery();
        $delivery_data  = $delivery_model->getAllByUser($user_id);

        if ($delivery_data->isEmpty()) {
            return;
        }
      
        foreach ($delivery_data as $value) {
            $follow = $this->queryFollow(
                $value->express_number, $value->express_code
            );

            if (!is_array($follow)) {
                return;
            }
             
            foreach ($value->product as $val) {
                $product[] = [
                    'name'  => $val->product_name ?? '',
                    'img'   => $val->coreproduct->product_img_r ?? '',
                ];
            }

            $result[] = [
                'order_sn'      => $value->coreorder->order_sn,
                'product_list'  => $product ?? [],
                'follow_status' => $follow['status_text'] ?? '',
                'follow_time'   => $follow['data'][0]['time'] ?? '',
                'follow_msg'    => $follow['data'][0]['context'] ?? '',
            ];
        }

        return $result;
    }

    /**
     * 查询快递物流跟踪信息
     *
     * @param   string  $exp_sn    快递单号
     * @param   string  $exp_code  快递公司编号
     * @return  array   物流数据
     */
    public function queryFollow($exp_sn, $exp_code='auto')
    {   
        $res = $this->aliyunExpressFollow($exp_sn, $exp_code);

        if (!is_array($res)) {
            return $res;
        }

        return $res;
    }

    /**
     * 阿里云查询物流跟踪信息
     *
     * @param   string  $exp_code  快递公司编号
     * @param   string  $exp_sn    快递单号
     * @return  array   物流数据
     * https://market.aliyun.com/products/57126001/cmapi010996.html?
     * spm=5176.2020520132.101.2.7de37218eB7rpV#sku=yuncode499600008
     */
    protected function aliyunExpressFollow($exp_sn, $exp_code)
    {
        $host       = 'https://ali-deliver.showapi.com';
        $path       = '/showapi_expInfo';
        $method     = 'GET';
        $appcode    = 'd9b1e4f6b3ee457390b7a1aad27f93c6';
        $headers    = [];

        array_push($headers, "Authorization:APPCODE " . $appcode);
        $querys = 'com='.$exp_code.'&nu='.$exp_sn;
        $bodys  = '';
        $url    = $host . $path . "?" . $querys;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }

        $res = curl_exec($curl);
        curl_close($curl);
        $res = json_decode($res, true);
      
        if (empty($res['showapi_res_body']['data'])) {
            return $res['showapi_res_body']['msg'] ?? '物流查询失败';
        }

        $status_map = $this->getStatusMap();
        $result['status'] = $res['showapi_res_body']['status'];
        $result['status_text'] = $status_map[$result['status']];

        foreach ($res['showapi_res_body']['data'] as $value) {
            $result['data'][] = [
                'time'      => $value['time'],
                'context'   => $value['context'],
            ];
        }

        return $result ?? '物流查询失败';
    }

    /**
     * 阿里云查询物流跟踪状态
     *
     * @return  array   物流状态
     */
    protected function getStatusMap()
    {
        return [
            '-1'    => '待查询',
            '0'     => '查询异常',
            '1'     => '暂无记录',
            '2'     => '在途中',
            '3'     => '派送中',
            '4'     => '已签收',
            '5'     => '用户拒签',
            '6'     => '疑难件',
            '7'     => '无效单',
            '8'     => '超时单',
            '9'     => '签收失败',
            '10'    => '退回',
        ];
    }

}
